
#include <sys/ioctl.h>
#include <net/if.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netpacket/packet.h>
#include <net/ethernet.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>

static int carac(char car)
{
   if((car >= '0') && (car <= '9')) return car - '0';
   car = toupper(car);
   if((car >= 'A') && (car <= 'F')) return car + 10 - 'A';
   return -1;
}

int main(int argc, char *argv[])
{
   char *device = "lo";
   unsigned char packet[2000];
   int i, len;
   char *pacoteenviar = "";

   int sock_fd = -1;
   struct ifreq ifr;
   struct sockaddr_ll sll;

   if(argc > 1) device = argv[1];
   if(argc > 2) pacoteenviar = argv[2];

   // Init data structures
   memset(&ifr, 0, sizeof(ifr));
   memset(&sll, 0, sizeof(sll));

   // Allocate a socket
   sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
   if (sock_fd == -1) {
      printf("socket: %s\n", strerror(errno));
      return(1);
   }
										   // Determine device id   
   strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
   if (ioctl(sock_fd, SIOCGIFINDEX, &ifr) == -1) {
      printf("ioctl SIOCGIFINDEX: %s\n", strerror(errno));
      return(2);
   }

   // Bind socket to interface
   sll.sll_family      = AF_PACKET;
   sll.sll_ifindex     = ifr.ifr_ifindex;
   sll.sll_protocol    = htons(ETH_P_ALL);
   if (bind(sock_fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
      printf("bind: %s\n", strerror(errno));
      return(3);
   }

   if(strlen(pacoteenviar) > 0) {
      len = 0;
      while(*pacoteenviar != '\0') {
	 int car, car2;
	 car = carac(*pacoteenviar++);
	 if(car < 0) break;
	 car2 = carac(*pacoteenviar++);
	 if(car2 < 0) break;
	 car = (car << 4) | car2;
	 packet[len++] = car;
      }
      write(sock_fd, packet, len);
      return 0;
   }

   for(;;) {
      static int pacote = 0;
      len = recvfrom(sock_fd, packet, 2000, 0, NULL, NULL);
      if (len == -1) {
	 printf("bind: %s\n", strerror(errno));
	 return(3);
      }
      printf("Len: %d:", len);
      for(i = 0; i < len; i++) {
	 printf("%s%02X", i & 1 ? "" : " ", packet[i]);
      }
      printf("\n");
      pacote++;
   }
   return 0;
}

